package sc

import (
	ctrl "huzhen/controllers"
	"huzhen/controllers/db"
	"net/http"
	"encoding/json"
	"fmt"
	"web/schema"
	"strconv"
)



func InitHandlers() {
	ctrl.HMAP["/app/sc/cdList"] = cdList // commodity 展示*/
	ctrl.HMAP["/app/sc/fincoms"] = fincoms
	ctrl.HMAP["/app/sc/getcoms"] = getCommodity
	ctrl.HMAP["/app/sc/updatecoms"] = updateCommodity
	ctrl.HMAP["/app/sc/insertcoms"] = insertCommodity
	ctrl.HMAP["/app/sc/buycom"] = buyCommodity
	ctrl.HMAP["/app/sc/getbill"] = getBillAll
}

type Bills struct {
	db.BillAll    `xorm:"extends"`
	db.Commodity `xorm:"extends"`
	db.Users `xorm:"extends"`
}

func (Bills) TableName() string {
	return "bill_all"
}

type Commodity struct {
	Id string  `json:"id"`
	Name string  `json:"name"`
	Stock string  `json:"stock"`
	Com_class string  `json:"com_class"`
	Sold string  `json:"sold"`
	Price string  `json:"price"`
}

func fincoms(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	w.Header().Set("Access-Control-Allow-Origin", "*")
	id := r.FormValue("id")
	sql := "SELECT * FROM commodity where id="+id+";"
	rowArray := db.Query(sql)
	var com Commodity
	for _, row := range rowArray {
		com.Id = string(row["id"])
		com.Name = string(row["name"])
		com.Stock = string(row["stock"])
		com.Com_class = string(row["com_class"])
		com.Sold = string(row["sold"])
		com.Price = string(row["price"])
		js1, _ := json.Marshal(com)
		fmt.Println(string(js1))
		w.Write([]byte("{'res':0,'data':"+string(js1)+"}"))
	}




}
func cdList(w http.ResponseWriter, r *http.Request) {

	w.Header().Set("Access-Control-Allow-Origin", "*")
	sql := "SELECT * FROM commodity"
	rowArray := db.Query(sql)
	coms := make([]map[string]string,8)
	for i, row := range rowArray {
		coms[i]=make(map[string]string)
		for k,v:=range row{
			coms[i][k]=string(v)
		}
	}
	js1,_ := json.Marshal(coms)
	fmt.Println(string(js1))
	w.Write([]byte("{'res':0,'data':"+string(js1)+"}"))

}

func getCommodity(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")
	eng := db.GetEngine()
	var tables []db.Commodity
	table := new(db.Commodity)
	n := schema.BasicQuery(eng, r, []string{"id", "name","stock","com_class","sold","price"}, &tables, table)
	fs := `[%d,"%s",%d,%d,%d,%f],`
	s := ""
	for _, u := range tables {
		s += fmt.Sprintf(fs, u.Id, u.Name,u.Stock,u.ComClass,u.Sold,u.Price)
	}
	fs = `{"count":%d,"rows":[%s]}`
	w.Write([]byte(fmt.Sprintf(fs, n, s)))
}

func insertCommodity(w http.ResponseWriter, r *http.Request) {
	eng := db.GetEngine()
	tables := &db.Commodity{}
	schema.FormParse(r,tables)
	affected,err:=eng.Insert(tables)
	if err!=nil{
		w.Write([]byte("{'err':'数据库错误'}"))
		return
	}
	if affected==0{
		w.Write([]byte("{'err':'插入失败，请检查信息'}"))
		return
	}else {
		w.Write([]byte("{'err':'插入成功'}"))
		return
	}
	w.Write([]byte("{'err':'未知错误'}"))
}

func updateCommodity(w http.ResponseWriter, r *http.Request) {
	eng := db.GetEngine()
	tables := &db.Commodity{}
	schema.FormParse(r,tables)
	affected,err:=eng.Table(new(db.Commodity)).Id(tables.Id).Update(map[string]interface{}{
		"name":tables.Name,"stock":tables.Stock,"com_class":tables.ComClass,"sold":tables.Sold,"price":tables.Price})
	if err!=nil{
		w.Write([]byte("{'err':'数据库错误'}"))
		return
	}
	if affected==0{
		w.Write([]byte("{'err':'找不到这条数据'}"))
		return
	}else {
		w.Write([]byte("{'err':'修改成功'}"))
		return
	}
	w.Write([]byte("{'err':'找不到这条数据'}"))
}

func buyCommodity(w http.ResponseWriter, r *http.Request){
	r.ParseForm()
	tables := &db.BillAll{}
	sql := "select id from users where accounts = '"+r.FormValue("accounts")+"';"
	rowArray := db.Query(sql)
	tables.State,_ = strconv.Atoi(r.FormValue("id"))
	tables.UserId,_ = strconv.Atoi(string(rowArray[0]["id"]))
	tables.Numbers,_ = strconv.Atoi(r.FormValue("numbers"))
	tables.Psf=1.00
	fmt.Println(tables)
	eng :=db.GetEngine()
	eng.Insert(tables)
	w.Write([]byte("修改成功"))

}
func getBillAll(w http.ResponseWriter, r *http.Request) {
	eng := db.GetEngine()
	var tables []Bills
	table := new(Bills)
	n := schema.JoindQuery(eng, r, []string{"bill_all.id", "users.name","bill_all.numbers","bill_all.psf","commodity.name"}, &tables, table,
		[][]string{{"INNER", "users", "bill_all.user_id = users.id"},
			{"INNER", "commodity", "bill_all.state = commodity.id"}})
	fs := `[%d,"%s",%d,%f,"%s"],`
	s := ""
	for _, u := range tables {
		s += fmt.Sprintf(fs, u.BillAll.Id, u.Users.Name,u.BillAll.Numbers,u.BillAll.Psf,u.Commodity.Name)
	}
	fs = `{"count":%d,"rows":[%s]}`
	w.Write([]byte(fmt.Sprintf(fs, n, s)))
}
